import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../views/app/app_view_404.dart';
import '../views/app/app_view_model.dart';
import '../views/auth/auth_view_main.dart';
import '../views/dashboard/dashboard_view_main.dart';
import '../views/layout/layout_main.dart';
import '../views/schedule/school_daily_schedule_view_main.dart';
import '../views/school/school_view_main.dart';
import '../views/semester/semester_view_main.dart';
import '../views/test/test_batch_view_main.dart';
import '../views/test/test_level_view_main.dart';
import '../views/timetable/school_class_timetable_view_main.dart';
import '../views/view_type.dart';

///应用路由-枚举
enum AppRote {
  auth('auth', '/auth', '登录'),
  setting('setting', '/setting', '配置'),
  dashboard('dashboard', '/dashboard', 'dashboard'),
  semester('semester', '/semester', '学年学期'),
  semesterEdit('semester-edit', '/semester/edit', '学年学期'),
  school('school', '/school', '学校管理'),
  schoolEdit('school-edit', '/school/edit', '学校'),
  clazz('class', '/class', '班级管理'),
  student('student', '/student', '学生管理'),
  teacher('teacher', '/teacher', '教师管理'),
  schedule('schedule', '/schedule', '作息时间'),
  scheduleEdit('schedule-edit', '/schedule/edit', '作息时间'),
  timetable('timetable', '/timetable', '课表管理'),
  timetableEdit('timetable-edit', '/timetable/edit', '课表'),
  testLevel('test-level', '/test-level', '考试等级'),
  testLevelEdit('test-level-edit', '/test-level/edit', '考试等级'),
  testBatch('test-batch', '/test-batch', '考试批次'),
  testBatchEdit('test-batch-edit', '/test-batch/edit', '考试批次'),
  notfound('404', '/404', ''),
  ;

  final String name, path, title;

  const AppRote(this.name, this.path, this.title);

  ///跳转
  void go(final BuildContext ctx) => ctx.go(getRotePath(this));
}

///获取应用路由名称
String getRoteName(final AppRote app) => app.name;

///获取应用路由路由
String getRotePath(final AppRote app, [final AppRote? parent]) {
  String path = app.path;
  if (parent != null) {
    final String prefix = parent.path;
    if (path.startsWith(prefix)) {
      path = path.substring(prefix.length);
    }
  }
  return path;
}

///获取应用路由标题
String getRoteTitle(final AppRote app) => app.title;

final rootNavigatorKey = GlobalKey<NavigatorState>();
final _shellNavigatorKey = GlobalKey<NavigatorState>();

final router = GoRouter(
  navigatorKey: rootNavigatorKey,
  initialLocation: getRotePath(AppRote.dashboard),
  routes: [
    ShellRoute(
      navigatorKey: _shellNavigatorKey,
      builder: (context, state, child) => LayoutMain(
        shellContext: _shellNavigatorKey.currentContext,
        child: child,
      ),
      redirect: (context, state) async {
        final model = context.read<AppViewModel>();
        final bool isAuth = await model.isAuth();
        debugPrint('redirect[${state.fullPath}]=>auth: $isAuth');
        if (!isAuth) {
          return getRotePath(AppRote.auth);
        }
        return null;
      },
      routes: [
        //首页
        GoRoute(
          name: getRoteName(AppRote.dashboard),
          path: getRotePath(AppRote.dashboard),
          builder: (_, __) => const DashboardViewMain(),
        ),
        //学年学期
        GoRoute(
          name: getRoteName(AppRote.semester),
          path: getRotePath(AppRote.semester),
          builder: (_, __) => const SemesterViewMain(type: ViewType.list),
          routes: [
            //edit
            GoRoute(
              name: getRoteName(AppRote.semesterEdit),
              path: getRotePath(AppRote.semesterEdit, AppRote.semester),
              builder: (_, state) {
                final id = state.uri.queryParameters['id'] ?? '';
                return SemesterViewMain(type: ViewType.edit, id: id);
              },
            ),
          ],
        ),
        //学校
        GoRoute(
          name: getRoteName(AppRote.school),
          path: getRotePath(AppRote.school),
          builder: (_, __) => const SchoolViewMain(type: ViewType.list),
          routes: [
            //edit
            GoRoute(
              name: getRoteName(AppRote.schoolEdit),
              path: getRotePath(AppRote.schoolEdit, AppRote.school),
              builder: (_, state) {
                final id = state.uri.queryParameters['id'] ?? '';
                return SchoolViewMain(type: ViewType.edit, id: id, tab: 0);
              },
            ),
          ],
        ),
        //作息时间
        GoRoute(
          name: getRoteName(AppRote.schedule),
          path: getRotePath(AppRote.schedule),
          builder: (_, state) {
            final schoolId = state.uri.queryParameters['schoolId'] ?? '';
            return SchoolDailyScheduleViewMain(
              type: ViewType.list,
              schoolId: schoolId,
            );
          },
          routes: [
            //edit
            GoRoute(
              name: getRoteName(AppRote.scheduleEdit),
              path: getRotePath(AppRote.scheduleEdit, AppRote.schedule),
              builder: (_, state) {
                final schoolId = state.uri.queryParameters['schoolId'] ?? '';
                final id = state.uri.queryParameters['id'] ?? '';
                return SchoolDailyScheduleViewMain(
                  type: ViewType.edit,
                  schoolId: schoolId,
                  id: id,
                );
              },
            ),
          ],
        ),
        //班级课表
        GoRoute(
          name: getRoteName(AppRote.timetable),
          path: getRotePath(AppRote.timetable),
          builder: (_, state) {
            final schoolId = state.uri.queryParameters['schoolId'] ?? '';
            return SchoolClassTimetableViewMain(
              type: ViewType.list,
              schoolId: schoolId,
            );
          },
          routes: [
            //edit
            GoRoute(
              name: getRoteName(AppRote.timetableEdit),
              path: getRotePath(AppRote.timetableEdit, AppRote.timetable),
              builder: (_, state) {
                final schoolId = state.uri.queryParameters['schoolId'] ?? '';
                final id = state.uri.queryParameters['id'] ?? '';
                return SchoolClassTimetableViewMain(
                  type: ViewType.edit,
                  schoolId: schoolId,
                  id: id,
                );
              },
            )
          ],
        ),
        //考试等级
        GoRoute(
          name: getRoteName(AppRote.testLevel),
          path: getRotePath(AppRote.testLevel),
          builder: (_, __) => TestLevelViewMain(type: ViewType.list),
          routes: [
            //edit
            GoRoute(
              name: getRoteName(AppRote.testLevelEdit),
              path: getRotePath(AppRote.testLevelEdit, AppRote.testLevel),
              builder: (_, state) {
                final id = state.uri.queryParameters['id'] ?? '';
                return TestLevelViewMain(
                  type: ViewType.edit,
                  id: id,
                );
              },
            )
          ],
        ),
        //考试批次
        GoRoute(
          name: getRoteName(AppRote.testBatch),
          path: getRotePath(AppRote.testBatch),
          builder: (_, __) => TestBatchViewMain(type: ViewType.list),
          routes: [
            //edit
            GoRoute(
              name: getRoteName(AppRote.testBatchEdit),
              path: getRotePath(AppRote.testBatchEdit, AppRote.testBatch),
              builder: (_, state) {
                final id = state.uri.queryParameters['id'] ?? '';
                return TestBatchViewMain(type: ViewType.edit, id: id);
              },
            )
          ],
        ),
      ],
    ),
    //Auth
    GoRoute(
      name: getRoteName(AppRote.auth),
      path: getRotePath(AppRote.auth),
      builder: (_, __) => const AuthViewMain(),
    ),
    //404
    GoRoute(
      name: getRoteName(AppRote.notfound),
      path: getRotePath(AppRote.notfound),
      builder: (_, __) => const AppView404(),
    ),
  ],
);
